import info.gridworld.actor.Actor;
import info.gridworld.grid.Grid;
import info.gridworld.grid.Location;

import java.awt.Color;
import java.util.ArrayList;

/**
 * A <code>ChameleonCritter</code> takes on the color of neighboring actors as
 * it moves through the grid. <br />
 * The implementation of this class is testable on the AP CS A and AB exams.
 */
public class ChameleonKid extends ChameleonCritter
{
	private static final double DARKENING_FACTOR = 0.05;
	/**
     * darken the critter like flowers
     */
	private void darken()
    {
    	Color c = getColor();
    	int r = (int)(c.getRed() * (1 - DARKENING_FACTOR));
    	int b = (int)(c.getBlue() * (1 - DARKENING_FACTOR));
    	int g = (int)(c.getGreen() * (1 - DARKENING_FACTOR));
    	setColor(new Color(r, g, b));
    	
    }
	
	/**
	 * A ChameleonKid gets the actors in the two locations immediately in front,
	 * at back
	 * @return a list of actors occupying two locations
	 */
	public ArrayList<Actor> getActors()
	{
		ArrayList<Actor> actors = new ArrayList<Actor>();
		int[] dirs = {Location.AHEAD, Location.HALF_CIRCLE};
		for (Location loc : getLocationsInDirections(dirs))
		{
			Actor a = getGrid().get(loc);
			if (a != null)
			{
				actors.add(a);
			}
		}
		return actors;
	}
	
	/**
     * Randomly selects a neighbor and changes this critter's color to be the
     * same as that neighbor's. If there are no neighbors, no action is taken.
     */
    public void processActors(ArrayList<Actor> actors)
    {
        int n = actors.size();
        if (n == 0)
        {
        	darken();
        	return;
        }
            
        int r = (int) (Math.random() * n);

        Actor other = actors.get(r);
        setColor(other.getColor());
    }
    
	/**
	 * A ChameleonKid gets the actors' locations in the two locations immediately in front,
	 * at back
	 * @return a list of actors' locations occupying two locations
   */
	public ArrayList<Location> getLocationsInDirections(int[] directions)
	{
	    ArrayList<Location> locs = new ArrayList<Location>();
	    Grid<Actor> grid = getGrid();
	    Location location = getLocation();
	    for (int d : directions)
	    {
	      Location neighborLocation = location.getAdjacentLocation(getDirection() + d);
	      if (grid.isValid(neighborLocation))
	      {
	        locs.add(neighborLocation);
	      }
	    }
	    return locs;
	 }
    
}
